<template>
  <a-modal
    :visible="visible"
    :title="editMode ? '编辑角色' : '创建角色'"
    :confirm-loading="loading"
    :maskClosable="false"
    :width="600"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
    >
      <div class="modal-content">
        <a-form-item label="所属应用" name="appId">
          <a-select
            v-model:value="formData.appId"
            placeholder="请选择所属应用"
            :disabled="editMode"
            show-search
            :filter-option="filterApplicationOption"
          >
            <a-select-option
              v-for="app in applicationList"
              :key="app.id"
              :value="app.id"
            >
              {{ app.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="角色名称" name="name">
          <a-input
            v-model:value="formData.name"
            placeholder="请输入角色名称"
            :disabled="editMode"
          />
        </a-form-item>
        <a-form-item label="角色编码" name="code">
          <a-input
            v-model:value="formData.code"
            placeholder="请输入角色编码"
            :disabled="editMode"
          />
        </a-form-item>
        <a-form-item label="角色描述" name="description">
          <a-textarea
            v-model:value="formData.description"
            placeholder="请输入角色描述"
            :auto-size="{ minRows: 3, maxRows: 5 }"
          />
        </a-form-item>
      </div>
    </a-form>

    <template #footer>
      <div class="form-footer">
        <a-button class="cancel-btn" @click="handleCancel">取消</a-button>
        <a-button
          type="primary"
          class="submit-btn"
          :loading="loading"
          @click="handleSubmit"
          >保存</a-button
        >
      </div>
    </template>
  </a-modal>
</template>

<script setup>
import { ref, reactive, watch, defineProps, defineEmits, onMounted } from "vue";
import { message } from "ant-design-vue";
import { createRole, updateRole } from "@/api/role";
import { getApplicationList } from "@/api/application";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  editMode: {
    type: Boolean,
    default: false,
  },
  roleData: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(["update:visible", "success"]);

// 表单引用
const formRef = ref(null);

// 组件挂载时获取应用列表
onMounted(() => {
  fetchApplicationList();
});

// 获取应用列表
const fetchApplicationList = async () => {
  try {
    const res = await getApplicationList({
      pageNum: 1,
      pageSize: 1000,
      status: "ENABLE",
    });
    applicationList.value = res.data.items || [];
  } catch (error) {
    console.error("获取应用列表失败:", error);
    message.error("获取应用列表失败");
  }
};

// 应用搜索过滤
const filterApplicationOption = (input, option) => {
  const app = applicationList.value.find((app) => app.id === option.value);
  if (!app) return false;
  const searchText = input.toLowerCase();
  return (
    app.name.toLowerCase().includes(searchText)
  );
};

// 加载状态
const loading = ref(false);

// 应用列表
const applicationList = ref([]);

// 表单数据
const formData = reactive({
  appId: undefined,
  name: "",
  code: "",
  description: "",
});

// 表单验证规则
const rules = {
  appId: [
    { required: true, message: "请选择所属应用", trigger: "change" },
  ],
  name: [
    { required: true, message: "请输入角色名称", trigger: "blur" },
    { max: 50, message: "角色名称不能超过50个字符", trigger: "blur" },
  ],
  code: [
    { required: true, message: "请输入角色编码", trigger: "blur" },
    {
      pattern: /^[A-Z_]+$/,
      message: "角色编码只能包含大写字母和下划线",
      trigger: "blur",
    },
    { max: 50, message: "角色编码不能超过50个字符", trigger: "blur" },
  ],
  description: [
    { max: 200, message: "角色描述不能超过200个字符", trigger: "blur" },
  ],
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  Object.assign(formData, {
    appId: undefined,
    name: "",
    code: "",
    description: "",
  });
};

// 监听编辑模式和角色数据变化
watch(
  () => [props.visible, props.editMode, props.roleData],
  ([visible, editMode, roleData]) => {
    try {
      if (visible) {
        if (editMode && roleData && typeof roleData === "object") {
          // 编辑模式，填充表单数据
          Object.assign(formData, {
            appId: roleData.appId || undefined,
            name: roleData.name || "",
            code: roleData.code || "",
            description: roleData.description || "",
          });
        } else if (!editMode) {
          // 创建模式，重置表单为默认值
          Object.assign(formData, {
            appId: undefined,
            name: "",
            code: "",
            description: "",
          });
        }
      } else {
        // 对话框关闭，重置表单
        resetForm();
      }
    } catch (error) {
      console.error("Watcher error in CreateRole:", error);
      // 发生错误时重置表单到安全状态
      resetForm();
    }
  },
  { immediate: true }
);

// 取消操作
const handleCancel = () => {
  emit("update:visible", false);
};

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    loading.value = true;

    try {
      if (props.editMode) {
        // 编辑角色 - 确保有有效的角色ID
        if (!props.roleData?.id) {
          throw new Error("角色ID不存在，无法更新");
        }
        await updateRole(props.roleData.id, formData);
        message.success("角色更新成功");
      } else {
        // 创建角色
        await createRole(formData);
        message.success("角色创建成功");
      }
      emit("update:visible", false);
      emit("success");
    } catch (error) {
      message.error(props.editMode ? "更新角色失败" : "创建角色失败");
    } finally {
      loading.value = false;
    }
  } catch (error) {}
};
</script>

<style lang="scss" scoped>
.form-footer {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;

  .cancel-btn {
    margin-right: 16px;
    min-width: 80px;
  }

  .submit-btn {
    min-width: 80px;
  }
}
</style>
